﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Principal;
using System.Threading;
using System.Web;
using System.Web.Mvc;
using MvcApplication2.Exceptions;
using MvcApplication2.Helpers;
using MvcApplication2.Services;
using MvcApplication2.Ultilities;
using MvcApplication2.Ultilities.Enums;

namespace MvcApplication2.Controllers
{
    public class BaseController : Controller
    {
        public BaseController() : this(DependencyResolver.Current.GetService<IEmployeeService>())
        {
        }

        public BaseController(IEmployeeService employeeService)
        {
            SessionHelper = new SessionHelper();
        }

        protected ISessionHelper SessionHelper;

        private void RedirectToAccessDenied(AuthorizationContext filterContext)
        {
            System.Web.HttpContext.Current.Session[Constant.UserPermission] = UserPermission.AccessDenied;
            filterContext.Result = new RedirectResult("~/Error/AccessDenied");
        }

        protected override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            if (TempData[Constant.ModalState] != null && !ModelState.Equals(TempData[Constant.ModalState]))
                ModelState.Merge((ModelStateDictionary)TempData[Constant.ModalState]);

            base.OnActionExecuted(filterContext);
        }

        protected override void OnAuthorization(AuthorizationContext filterContext)
        {
            var user = SessionHelper.Get<string>(Constant.CurrentUser);
            if (user == null)
            {
                var loginUser = User.Identity.Name;
                if (loginUser == null)
                {
                    filterContext.Result = new RedirectResult("~/Error/AccessDenied");
                    return;
                }

                SessionHelper.Set(Constant.CurrentUser, loginUser);
            }

            var roleKeys = SessionHelper.Get<IList<RoleKey>>(Constant.RoleKeys);// (IList<RoleKey>)System.Web.HttpContext.Current.Session[Constant.RoleKeys];
            // alway check role from database for every request except ajax request 
            if (!filterContext.HttpContext.Request.IsAjaxRequest() || roleKeys == null)
            {
                roleKeys = new List<RoleKey> {RoleKey.ADMIN};
                SessionHelper.Set(Constant.RoleKeys, roleKeys);
                //System.Web.HttpContext.Current.Session[Constant.RoleKeys] = roleKeys;
            }

            try
            {
                //var slPrincipal = Thread.CurrentPrincipal as SLPrincipal;
                //if (slPrincipal == null)
                //{
                //    Thread.CurrentPrincipal = new SLPrincipal(WindowsIdentity.GetCurrent(),
                //       SessionHelper.Get<int>(Constant.UserId),
                //       SessionHelper.Get<string>(Constant.UserLoginName),
                //       SessionHelper.Get<string>(Constant.UserLoginId));
                //}
            }
            catch (Exception ex)
            {
               //Log exception
            }

            base.OnAuthorization(filterContext);
        }

        //protected void ShowMessage(string message, string title = "", MessageType messageType = MessageType.Success)
        //{
        //    TempData["MessageType"] = (int)messageType;
        //    TempData["Title"] = title;
        //    TempData["Message"] = message;
        //}

        //protected void ShowMessage(DataUpdateStatus dataUpdateStatus, string controllerName = "")
        //{
        //    switch (dataUpdateStatus)
        //    {
        //        case DataUpdateStatus.Default:
        //            break;
        //        case DataUpdateStatus.Created:
        //            ShowMessage(string.Format(CreateMessage, controllerName));
        //            break;
        //        case DataUpdateStatus.Updated:
        //            ShowMessage(string.Format(UpdateMessage, controllerName));
        //            break;
        //        case DataUpdateStatus.Deleted:
        //            break;
        //        case DataUpdateStatus.Error:
        //            ShowMessage(string.Format(InvalidMessage, controllerName), messageType: MessageType.Error);
        //            break;
        //    }
        //}

        protected override void OnException(ExceptionContext filterContext)
        {
            //LoggerHelper.Log(filterContext.Exception.Message, filterContext.Exception);
            filterContext.ExceptionHandled = true;
            if (filterContext.Exception is ItemNotFoundException)
            {
                filterContext.Result = new RedirectResult("~/Error/NotFound");
            }
            else if (filterContext.Exception is CustomException)
            {
                TempData["ERROR_MESSAGE"] = filterContext.Exception.Message;
                filterContext.Result = new RedirectResult("~/Error/CustomError");
            }
            else
            {
                TempData["LAST_ERROR"] = filterContext.Exception;
                filterContext.Result = new RedirectResult("~/Error/ServerError");
            }
        }

    }
}